<template>
  <div class="update-avatar">
    <img :src="img" ref="img" />
    <div class="toolbar">
      <span @click="$emit('cancel')">取消</span>
      <span @click="onSave">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user.js'
import { Toast } from 'vant'
export default {
  data () {
    return {

    }
  },

  mounted () {
    const img = this.$refs.img
    this.cropper = new Cropper(img, {
      background: false,
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      dragMode: 'move',
      viewMode: 1,
      cropBoxResizable: false
    })
  },

  props: {
    img: {
      type: String,
      required: true
    }
  },

  created () {

  },

  methods: {
    onSave () {
      console.log('裁剪图片')
      // 1. 后端裁剪,前端提供坐标
      // console.log(this.cropper.getData())
      // 2. 前端裁剪
      // console.log(this.cropper.getCroppedCanvas())
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        console.log(blob)
        // 后端要的是 form-data
        const formData = new FormData()
        formData.append('photo', blob)
        // 将formData交给后端 包含了 裁剪的图片
        try {
          const res = await updateUserAvatar(formData)
          console.log(res)
          Toast.success('裁剪成功')
          this.$emit('cancel')
          this.$emit('on-success', res.photo)
        } catch (err) {
          Toast('裁剪失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
